package com.asman.worker.rn_ui;

import android.app.Activity;

import com.asman.oss.Config;
import com.asman.worker.multishow.ImageTitle;
import com.asman.worker.multishow.MultiShowActivity;
import com.asman.worker.widgets.multiFile.ImageUploadData;
import com.asman.worker.widgets.singleFile.SingleImageUploadLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author ybk
 * @date :2019-10-15 10:44
 * @desc:
 */
public class NativeSingleUploadMulti extends SimpleViewManager<SingleImageUploadLayout> {

    public static final String REACT_CLASS = "NativeSingleUploadMulti";

    private ThemedReactContext reactContext;

    @Override
    public @Nonnull
    String getName() {
        return REACT_CLASS;
    }

    @Nonnull
    @Override
    protected SingleImageUploadLayout createViewInstance(@Nonnull ThemedReactContext reactContext) {
        this.reactContext = reactContext;
        SingleImageUploadLayout view = new SingleImageUploadLayout(reactContext.getCurrentActivity() == null ? reactContext : reactContext.getCurrentActivity());
        view.setReactContext(reactContext);
        view.setOnCallBackListener(new SingleImageUploadLayout.OnCallBack() {
            @Override
            public void onAddClickListener() {
                if (intercept) {
                    callJSOnFirstClick(reactContext, view);
                }
            }

            @Override
            public void onDeleteClickListener(@NotNull ImageUploadData data) {
                super.onDeleteClickListener(data);
            }

            @Override
            public void onImageListener(@NotNull ImageUploadData data) {
                super.onImageListener(data);
                //查看图片
                if (view.getContext() instanceof Activity) {
                    List<ImageTitle> list = new ArrayList<>();
                    list.add(new ImageTitle(data.getLocalPath() == null ? "" : data.getLocalPath(), ""));
                    MultiShowActivity.Companion.start((Activity) view.getContext(), list, 0);
                }
            }
        });
        return view;
    }

    private boolean intercept = false;

    @ReactProp(name = "interceptFirstClick", defaultBoolean = false)
    public void setInterceptFirstClick(SingleImageUploadLayout view, Boolean intercept) {
        this.intercept = intercept;
    }

    /**
     * 这是可以选择的 多媒体类型
     *
     * @param view SingleImageUploadLayout
     * @param type type 1：照片，2：照片+视频
     */
    @ReactProp(name = "multiType", defaultDouble = 0)
    public void setMultiType(SingleImageUploadLayout view, Integer type) {
        if (type == 1) {
            view.setVideoEnable(false);
        } else if (type == 2) {
            view.setVideoEnable(true);
        }
    }

    @ReactProp(name = "title", defaultDouble = 0)
    public void setTitle(SingleImageUploadLayout view, String title) {
        view.setTitle(title);
    }

    @ReactProp(name = "sts", defaultDouble = 0)
    public void setSTS(SingleImageUploadLayout view, String sts) {
        Config.STS_SERVER_URL = sts;
    }

    @ReactProp(name = "bucketName")
    public void setBucketName(SingleImageUploadLayout view, String bucketName) {
        view.setBucketName(bucketName);
    }

    @ReactProp(name = "endpoint")
    public void setEndpoint(SingleImageUploadLayout view, String endpoint) {
        view.setEndpoint(endpoint);
    }

    /**
     * @param reactContext ThemedReactContext
     * @param view         AddImageGridLayout
     */
    private void callJSOnFirstClick(@Nonnull ThemedReactContext reactContext, SingleImageUploadLayout view) {
        // 创建数据传递信使，类似于Android中的Bundle
        WritableMap data = Arguments.createMap();
//        data.putString("status", String.valueOf(playStatus));// key用于在RN中获取传递的数据
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                view.getId(), // RN层原生层根据id绑定在一起
                EVENT_NAME_ON_FIRST_CLICK, // 事件名称
                data // 传递的数据
        );
    }

    /**
     * @param reactContext ThemedReactContext
     * @param view         AddImageGridLayout
     */
    private void callJSIsAllSuccess(@Nonnull ThemedReactContext reactContext, SingleImageUploadLayout view) {
        // 创建数据传递信使，类似于Android中的Bundle
        boolean isSuccess = (view.getData().getStatus() == 0 || view.getData().getStatus() == 3);
        WritableMap data = Arguments.createMap();
        data.putBoolean("isSuccess", isSuccess);// key用于在RN中获取传递的数据
        if (isSuccess) {
            data.putString("path", view.data.getUrl() == null ? "" : view.data.getUrl());// key用于在RN中获取传递的数据
        }
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                view.getId(), // RN层原生层根据id绑定在一起
                EVENT_NAME_ON_FILE_PATH_CALL_BACK, // 事件名称
                data // 传递的数据
        );
    }

    @Override
    public void updateProperties(@Nonnull SingleImageUploadLayout viewToUpdate, ReactStylesDiffMap props) {
        super.updateProperties(viewToUpdate, props);
    }

    @Nullable
    @Override
    public Map getExportedCustomDirectEventTypeConstants() {
        return MapBuilder.of(
                EVENT_NAME_ON_FIRST_CLICK, MapBuilder.of("registrationName", EVENT_NAME_ON_FIRST_CLICK),
                EVENT_NAME_ON_FILE_PATH_CALL_BACK, MapBuilder.of("registrationName", EVENT_NAME_ON_FILE_PATH_CALL_BACK)
        );
    }

    //Native  通知 RN
    public static final String EVENT_NAME_ON_FIRST_CLICK = "onFirstClick";
    public static final String EVENT_NAME_ON_FILE_PATH_CALL_BACK = "onFilePathCallBack";

    //接受RN 的消息
    private static final String HANDLE_GET_FILE_PATHS_NAME = "getFilePaths"; // 是否全部上传完
    private static final String HANDLE_SHOW_TAKE_PHOTO_NAME = "showTakePhoto"; // 展示拍照dialog
    private static final String HANDLE_DESTROY_NAME = "destroy"; // 销毁

    private static final int HANDLE_GET_FILE_PATHS = 1; // 是否全部上传完成
    private static final int HANDLE_SHOW_TAKE_PHOTO = 2; // 展示拍照dialog
    private static final int HANDLE_DESTROY = 3; // 销毁

    /**
     * 接收交互通知
     */
    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap() {
        return MapBuilder.of(
                HANDLE_GET_FILE_PATHS_NAME, HANDLE_GET_FILE_PATHS,
                HANDLE_SHOW_TAKE_PHOTO_NAME, HANDLE_SHOW_TAKE_PHOTO,
                HANDLE_DESTROY_NAME, HANDLE_DESTROY
        );
    }

    /**
     * 根据命令ID，处理对应任务
     *
     * @param view
     * @param commandId
     * @param args
     */
    @Override
    public void receiveCommand(@NotNull SingleImageUploadLayout view, int commandId, @Nullable ReadableArray args) {
        switch (commandId) {
            case HANDLE_GET_FILE_PATHS://是否全部上传完成
                if (args != null) {
                    callJSIsAllSuccess(reactContext, view);
                }
                break;
            case HANDLE_SHOW_TAKE_PHOTO:
                if (args != null) {
                    view.showPhotoDialog();
                }
                break;
            case HANDLE_DESTROY:
                if (args != null) {
                    view.onDestroy();
                }
                break;
            default:
                break;
        }
    }
}